package com.hypertech.core.ffmpeg.controller;

import com.hypertech.core.ffmpeg.model.Job;
import com.hypertech.core.ffmpeg.service.JobService;
import com.hypertech.core.ffmpeg.videoDao.FileInfo;
import com.hypertech.core.ffmpeg.videoDao.VideoDao;
import com.hypertech.core.ffmpeg.videoDao.VideoOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/video")
public class VideoController {
    private static String VIDEO_FILE_TYPE = ".flv";
    private static String IMAGE_FILE_TYPE = ".jpg";
   /* ffmpeg能解析的格式：（asx，asf，mpg，wmv，3gp，mp4，mov，avi，flv等）*/
    private static String[] UPLOAD_VIDEO_SUPPORT_TYPE={".avi",".mp4",".flv",".3gp",".asx",".asf",".mpg",".wmv",".mov"};
    @Autowired
    private VideoDao videoDao;

    @Autowired
    private JobService jobService;

    @Value("${ffmpeg.savePath}")
    private String savePath;

    @Value("${ffmpeg.convertPath}")
    private String convertPath;

    @RequestMapping("/upload")
    public String upload(MultipartFile video) throws Exception {

        if (video == null){return "请上传文件";}

        File savepath = new File(savePath);
        File convertpath = new File(convertPath);
        FileInfo.mkDir(savepath);
        FileInfo.mkDir(convertpath);

        String originalFilename = video.getOriginalFilename();//上传文件名
        String postName = originalFilename.substring(originalFilename.lastIndexOf("."));//原文件后缀名
        for (int i = 0; i < UPLOAD_VIDEO_SUPPORT_TYPE.length; i++) {
            if (!UPLOAD_VIDEO_SUPPORT_TYPE[i].equals(postName) && i>=UPLOAD_VIDEO_SUPPORT_TYPE.length-1){
                return "不支持该上传文件格式";
            }else if (UPLOAD_VIDEO_SUPPORT_TYPE[i].equals(postName)){
                break;
            }
        }
        UUID uuid = UUID.randomUUID();
        String filename= uuid + postName;
        File newFile =new File(savePath+filename);
        try {
            video.transferTo(newFile);//先保存上传的文件到指定目录
        } catch (IOException e) {
            return e.getMessage();
        }


        String src = savePath+filename;//源文件绝对路径

        String destprefix=convertPath+uuid;//转换文件名前缀

        /*视频*/
        String dest = destprefix+VIDEO_FILE_TYPE;

        List<String> commands = new ArrayList<String>();
        commands.add("ffmpeg");
        commands.add("-i");
        commands.add(src);
        commands.add("-vcodec");
        commands.add("libx264");
        commands.add("-preset");
        commands.add("ultrafast");
        commands.add("-profile:v");
        commands.add("baseline");
        commands.add("-acodec");
        commands.add("aac");
        commands.add("-strict");
        commands.add("experimental");
        commands.add("-qscale");//视频品质
        commands.add("6");//视频品质参数
        commands.add("-ab");
        commands.add("128k");
        commands.add("-y");//文件存在选择重写
        commands.add(dest);

        videoDao.runCmd(commands);

       /*截图
        * ffmpeg -i src.mp4  -y -f image2 -ss 8 -t 0.001 -s 1920x1080 test.jpg
        * */

        dest = destprefix+IMAGE_FILE_TYPE;
        List<String> jpgCommands = new ArrayList<String>();
        jpgCommands.add("ffmpeg");
        jpgCommands.add("-i");
        jpgCommands.add(src);
        jpgCommands.add("-f");
        jpgCommands.add("image2");
        jpgCommands.add("-ss");
        jpgCommands.add("0.001");
        jpgCommands.add("-y");
        jpgCommands.add(dest);

        videoDao.runCmd(jpgCommands);

        /*数据库保存*/
        Job job = new Job();
        job.setId(uuid.toString());
        job.setName(uuid.toString());
        job.setPhoto(uuid+IMAGE_FILE_TYPE);
        job.setVideo(uuid+VIDEO_FILE_TYPE);
        jobService.add(job);

        /*删除源文件*/
        File deleteFile = new File(src);
        if (deleteFile.exists()){
            deleteFile.delete();
        }

        return uuid.toString();
    }
}
